package cn.com.shuyangyang.controller;

import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.shuyangyang.common.Context;
import cn.com.shuyangyang.common.ExcelToUserData;
import cn.com.shuyangyang.common.UploadUserData;
import cn.com.shuyangyang.common.RequestContext;
import cn.com.shuyangyang.controller.response.ApplicationErrorResponse;
import cn.com.shuyangyang.controller.response.EmptyResponse;
import cn.com.shuyangyang.controller.response.ExceptionResponse;
import cn.com.shuyangyang.controller.response.NormalResponse;
import cn.com.shuyangyang.controller.response.Response;
import cn.com.shuyangyang.domain.LoginLog;
import cn.com.shuyangyang.domain.User;
import cn.com.shuyangyang.manager.UserManager;
import cn.com.shuyangyang.service.UserService;

@Controller
@RequestMapping("/user/")
public class UserController {
	Logger	logger	= LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private UserManager userManager;
	
	@Autowired
	private UploadUserData uploadUserData; 
	
	@Autowired
	private ExcelToUserData excelToUserData;

	@RequestMapping("login")
	@ResponseBody
	public Response login(HttpServletRequest request, HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");
		try {
			Context context = new RequestContext(request);
			User user = userService.Login(context);
			if(user==null){
				return new ApplicationErrorResponse("登录失败，登录名、密码错误或者此用户被禁用！");
			}
			LoginLog loginLog = userManager.InitUserManager(user, context);
			HttpSession session = request.getSession();
			session.setAttribute("loginLogInfo", loginLog);
			return new NormalResponse(loginLog);
		} catch (Exception e) {
			logger.error("登录环节出现异常：",e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
	}
	
	@RequestMapping("password")
	@ResponseBody
	public Response password(HttpServletRequest request, HttpServletResponse response) {   
		response.setCharacterEncoding("utf-8");
		try {
			LoginLog loginLogInfo = (LoginLog) request.getSession().getAttribute("loginLogInfo");
			Context context = new RequestContext(request);
			return userService.chanPassword(loginLogInfo, context);
		} catch (Exception e) {
			logger.error("修改密码环节异常：",e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
	}
	
	@RequestMapping("logout")
	@ResponseBody
	public void logout(HttpServletRequest request, HttpServletResponse response){
		response.setCharacterEncoding("utf-8");
		try {
			LoginLog loginLogInfo = (LoginLog) request.getSession().getAttribute("loginLogInfo");
			userService.NormalLoginOut(loginLogInfo);
			request.getSession().removeAttribute("loginLogInfo");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("退出异常："+e);
		}
	}
	
	@RequestMapping("showUser")
	@ResponseBody
	public Response resp(HttpServletRequest req, HttpServletResponse resp){
		String start = req.getParameter("start");//起始页
        String limit = req.getParameter("limit");//每页数量
        int index = Integer.parseInt(start);  
        int pageSize = Integer.parseInt(limit);
        List<User> users = userService.FindUsersByPage(index, pageSize);
        long total = users.size();
        if(total>0){
			logger.debug("now {}" , "返回用户数据。。。");
			return new NormalResponse(users,userService.UserCount());
		}else{
			logger.debug("now {}" , "用户数据为空！");
			return new EmptyResponse("用户数据");
		}
	}
	
	@RequestMapping("addUser")
	@ResponseBody
	public Response addUser(HttpServletRequest request, HttpServletResponse response){
		response.setCharacterEncoding("utf-8");
		try {
			Context context = new RequestContext(request);
			User user = userService.getUserByLoginName(context);
			if(user!=null){
				return new ApplicationErrorResponse("已存在的用户名，请重新填写！");
			}
			userService.addUser(context);
			return new NormalResponse();
		} catch (Exception e) {
			logger.error("添加用户环节出现异常：",e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
	}
	
	@RequestMapping("crossUser")
	@ResponseBody
	public Response crossUser(HttpServletRequest request){
		try {
			Context context = new RequestContext(request);
			userService.crossUser(context);
			return new NormalResponse();
		} catch (Exception e) {
			logger.error("禁用用户环节出现异常：",e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
	} 
	
	@RequestMapping("tickUser")
	@ResponseBody
	public Response tickUser(HttpServletRequest request){
		try {
			Context context = new RequestContext(request);
			userService.tickUser(context);
			return new NormalResponse();
		} catch (Exception e) {
			logger.error("启用用户环节出现异常：",e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
	}
	
	@RequestMapping("loadUser")
	@ResponseBody
	public Response loadUser(HttpServletRequest request, HttpServletResponse response){
		response.setCharacterEncoding("utf-8");
		try {
			Context context = new RequestContext(request);
			User user = userService.getUserByLoginName(context);
			if(user!=null){
				return new NormalResponse(user);
			}else{
				return new EmptyResponse("用户");
			}
		} catch (Exception e) {
			logger.error("读取用户环节出现异常：",e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
	}
	
	@RequestMapping("updaetUser")
	@ResponseBody
	public Response updaetUser(HttpServletRequest request, HttpServletResponse response){
		response.setCharacterEncoding("utf-8");
		try {
			Context context = new RequestContext(request);
			userService.updateUser(context);
			return new NormalResponse();
		} catch (Exception e) {
			logger.error("修改用户环节出现异常：",e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
	}
	
	@RequestMapping("delUser")
	@ResponseBody
	public Response delUser(HttpServletRequest request){
		try {
			Context context = new RequestContext(request);
			userService.delUserByUserId(context);
			return new NormalResponse();
		} catch (Exception e) {
			logger.error("删除用户环节出现异常：",e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
	}
	
	@RequestMapping("uploadUsers")
	@ResponseBody
	public Response uploadUsers(HttpServletRequest request){
		try {
			return uploadUserData.UploadUser(request);
		} catch (Exception e) {
			logger.error("批量导入用户环节出现异常：",e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
	}
	
	@RequestMapping("exportUsersToExcel")
	@ResponseBody
	public void exportUsersToExcel(HttpServletRequest request,HttpServletResponse response){
		HSSFWorkbook workbook = excelToUserData.exportUserData();
		response.reset();  
		response.setContentType("application/msexcel;charset=UTF-8");
		String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xls";
        try {    
        	response.setHeader("Content-Disposition", "attachment;filename="+fileName);  
            OutputStream out = response.getOutputStream();    
            workbook.write(out);    
            out.flush();    
            out.close(); 
        } catch (Exception e) {    
            e.printStackTrace();    
        } 
	}
}
